<template>
	<view class="container">
		
		<!-- 用户信息部分 -->
		<view class="user-info-section">
			<view class="dropdowns">
				<picker @change="bindSchoolChange" :value="selectedSchoolIndex" :range="schoolList">
					<view class="dropdown-item">
						<text>{{schoolList[selectedSchoolIndex]}}</text>
						<u-icon
						  size="20"
						  name="arrow-down"
						></u-icon>
						
					</view>
				</picker>
				<picker v-show="!classPickerDisabled" @change="bindClassChange" :value="selectedClassIndex" :range="classNameList">
					<view class="dropdown-item">
						<text>{{classNameList[selectedClassIndex]}}</text>
						<u-icon
						  size="20"
						  name="arrow-down"
						></u-icon>
					</view>
				</picker>
				<text class="lesson-count">{{classHour}}</text>
			</view>
			<image class="avatar" :src="parenturl"></image>
		</view>

		<!-- 日历部分 -->
		<view class="calendar-section" v-show="showCalendar">
			<view class="calendar-search-row">
				<view class="date-input-row">
					<text class="date-label">日期</text>
					<input class="date-input" type="text" placeholder="请选择日期" v-model="selectedDate" readonly @click="showDatePicker = true" />
					<u-icon size="30" name="calendar" color="#999" @click="showDatePicker = true"></u-icon>
				</view>
			</view>
			<view class="calendar-month-nav-row">
				<text class="nav-arrow" @click="goToPreviousMonth">＜ 上一月</text>
				<text class="month" style="color: #4296E5;">{{currentYear}}-{{currentMonth}}</text>
				<text class="nav-arrow" @click="goToNextMonth">下一月 ＞</text>
			</view>
			<view class="calendar-grid">
				<!-- 星期头部 -->
				<view class="weekday-header">
					<text v-for="day in weekdays" :key="day">{{day}}</text>
				</view>
				<!-- 日期网格，动态渲染 -->
				<view class="days-row" v-for="(row, rowIndex) in calendarRows" :key="rowIndex">
					<text 
						v-for="(day, dayIndex) in row" 
						:key="dayIndex"
						:class="{
							'day': true,
							'gray': !day.isCurrentMonth,
							'selected': day.isCurrentMonth && day.isSelected
						}"
						@click="onCalendarDayClick(day)"
					>{{day.day}}</text>
				</view>
			</view>
		</view>

		<!-- 课程信息部分 -->
		<view class="course-info-scroll" v-show="showCalendar">
			<view class="course-info-section" v-if="selectedLessonDetails && selectedLessonDetails.length > 0">
				<view v-for="(lesson, index) in selectedLessonDetails" :key="index" class="lesson-item">
					<view class="time-display">
						<text class="time-icon">🕒</text>
						<text class="time-range">{{lesson.timePeriod}}</text>
					</view>
					<text class="course-name">课程：{{lesson.courseName}}</text>
					<text class="class-name">班级：{{lesson.claDescribe}}</text>
					<view class="divider" v-if="index < selectedLessonDetails.length - 1"></view>
				</view>
			</view>
			<view class="course-info-section" v-else>
				<view class="time-display">
					<text class="time-icon">🕒</text>
					<text class="time-range">无课程</text>
				</view>
				<text class="course-name">今日无课程</text>
				<text class="class-name"></text>
			</view>
		</view>


		<!-- 状态不对展示的 -->
		<view v-show="!showCalendar" style="height: 140px;width: 100%;text-align: center;line-height: 180px;font-size: 20px;color: #4296E5;">
			该班级已毕业
			</view>
		<!-- 底部导航栏 -->
		<tabBar></tabBar>
		
		<!-- 日期选择器 -->
		<u-datetime-picker
			:show="showDatePicker"
			mode="date"
			@confirm="confirmDate"
			@cancel="showDatePicker = false"
			:value="defaultPickerDate"
		></u-datetime-picker>
	</view>
</template>

<script>
	import {studentName,studentCla,parentUrl,courseInformation,dateSelectCourse} from "@/api/schedule.js"
	export default {
		data() {
			const today = new Date();
			return {
				parenturl:'',
				showCalendar:true,
				schoolList: [],
				classList: [],
				classNameList:[],
				selectedSchoolIndex: 0,
				selectedClassIndex: 0,
				classHour: '第 9 / 21 课时',
				classPickerDisabled: true,
				showDetailedSearch: false,
				selectedDate: uni.$u.timeFormat(today, 'yyyy-mm-dd'),
				showDatePicker: false,
				currentYear: today.getFullYear(),
				currentMonth: today.getMonth() + 1, // 月份是0-indexed，所以需要加1
				currentMonthLessons: [], // 存储当前月份的课程数据
				selectedCalendarDate: null, // 日历中选中的日期
				selectedLessonDetails: null, // 选中日期的课程详情
				weekdays: ['一', '二', '三', '四', '五', '六', '日'],
				calendarDays: [], // 用于日历网格所有日期的数组
				defaultPickerDate: today.getTime() // 将今天的日期作为时间戳用于日期选择器默认值
			}
		},
		computed: {
			calendarRows() {
				const rows = [];
				for (let i = 0; i < this.calendarDays.length; i += 7) {
					rows.push(this.calendarDays.slice(i, i + 7));
				}
				return rows;
			}
		},
		async onLoad() {
			try{
				const parentId = uni.getStorageSync('parentId');
				const data ={ parentId };
				//查询家长头像
				const parentU = await parentUrl(data);
				console.log(parentU.data.parent);
				this.parenturl = parentU.data.parent.parentUrl;
				
				//查询家长的孩子
				const studentRes = await studentName(data);
				this.schoolList = studentRes.data.StudentDtos.map(s => s.stuName);
				this.studentClass();
				
			}catch(err){
				uni.showToast({ title: '出错了', icon: 'error' });
				console.error(err);
			}
		},
		methods: {
			// 家长端的学生课程查询根据日期
			inquire(){
				// 已不需要单独调用，逻辑已合并到selectCalendarDate
			},
			//根据学生姓名查询班级信息
			async studentClass(){
				const datas = {
				    userName: this.schoolList[this.selectedSchoolIndex]
				};
				const classRes = await studentCla(datas);
				//存放在数组中
				this.classList=classRes.data.stus;
				//取出班级名
				this.classNameList = this.classList.map(clasrs => clasrs.claDescribe)
				//判断第一个班级是否是毕业班级
				if (this.classList.length > 0) {
				    if (this.classList[0].claStatus === 1) {
				      this.showCalendar = false;
				    } else {
				      this.showCalendar = true;
				    }
				  }
				 await this.fetchLessonsForMonth(this.currentYear, this.currentMonth, () => {
				  	// 默认选中今天
				  	const today = new Date();
				  	const todayString = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
				  	this.generateCalendarDays();
				  	// 在日历中找到今天的日期并选中
				  	const todayDay = this.calendarDays.find(day => day.fullDate === todayString);
				  	if (todayDay) {
				  		this.selectCalendarDate(todayDay);
				  	}
				  });
				console.log('班级信息:', classRes);
				
			},
			bindSchoolChange: function(e) {
				this.selectedSchoolIndex = e.detail.value;
				console.log(this.schoolList[this.selectedSchoolIndex]);
				//	查询班级信息
				this.studentClass();
				// 切换学生后，日历跳转到今天
				const today = new Date();
				const todayString = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
				this.selectedDate = todayString;
				this.currentYear = today.getFullYear();
				this.currentMonth = today.getMonth() + 1;
				this.fetchLessonsForMonth(this.currentYear, this.currentMonth, () => {
					const day = this.calendarDays.find(d => d.fullDate === this.selectedDate);
					if (day) {
						this.selectCalendarDate(day);
					}
				});
			},
			bindClassChange: function(e) {
				//查看选中的学生
				console.log(this.schoolList[this.selectedSchoolIndex]);
				this.selectedClassIndex = e.detail.value;
				console.log(this.classList[this.selectedClassIndex].claStatus);
		
				//如果班级状态是毕业状态，就不展示课表
				if(this.classList[this.selectedClassIndex].claStatus === 1){
					console.log(2444)
					this.showCalendar = false;
					return;
				}
				this.showCalendar = true;
				// 切换班级后，日历跳转到今天
				const today = new Date();
				const todayString = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
				this.selectedDate = todayString;
				this.currentYear = today.getFullYear();
				this.currentMonth = today.getMonth() + 1;
				this.fetchLessonsForMonth(this.currentYear, this.currentMonth, () => {
					const day = this.calendarDays.find(d => d.fullDate === this.selectedDate);
					if (day) {
						this.selectCalendarDate(day);
					}
				});
			},
			toggleDetailedSearch: function() {
				this.showDetailedSearch = !this.showDetailedSearch;
			},
			confirmDate(e) {
				this.selectedDate = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
				this.showDatePicker = false;
				// 解析选择的年份和月份
				const [year, month] = this.selectedDate.split('-').map(Number);
				// 如果月份或年份不同，则切换日历
				if (year !== this.currentYear || month !== this.currentMonth) {
					this.currentYear = year;
					this.currentMonth = month;
					// 重新查课表并刷新日历
					this.fetchLessonsForMonth(this.currentYear, this.currentMonth, () => {
						// 日历高亮对应日期
						const day = this.calendarDays.find(d => d.fullDate === this.selectedDate);
						if (day) {
							this.selectCalendarDate(day);
						}
					});
				} else {
					// 月份没变，直接高亮
					const day = this.calendarDays.find(d => d.fullDate === this.selectedDate);
					if (day) {
						this.selectCalendarDate(day);
					}
				}
			},
			// 模拟从数据库获取课程数据
			fetchLessonsForMonth(year, month, cb) {
				const monthStr = month < 10 ? '0' + month : '' + month;
				const startDate = `${year}-${monthStr}-01`;
				const lastDay = new Date(year, month, 0).getDate();
				const endDate = `${year}-${monthStr}-${lastDay}`;
				// 这里 startDate 和 endDate 就是月份开始时间，结束时间
				console.log(startDate);
				console.log(endDate);
				//如果是毕业班就不查课程
				if(this.classList[this.selectedClassIndex].claStatus === 1){
					console.log(271)
					return;
				}
				const data = {
					claId: this.classList[this.selectedClassIndex].claId,
					startDate,
					endDate
				}
				console.log(data);
				//调用api查询该月份的课程
				courseInformation(data).then(res =>{
					console.log(res)
					this.currentMonthLessons = res.data.courses || [];
					this.generateCalendarDays(); // 关键：刷新日历
					// 自动选中本月1号
					const firstDay = this.calendarDays.find(day => day.isCurrentMonth && day.day === 1);
					if (firstDay) {
						this.selectCalendarDate(firstDay);
					}
					if (cb) cb();
				}).catch(err => {
					uni.showToast({ title: '出错了', icon: 'error' });
					if (cb) cb();
				});
			},
			selectCalendarDate(day) {
				// 只允许选择当前月份且未灰显的日期
				if (!day.isCurrentMonth) {
					return;
				}

				// 先清除所有选中状态，防止多选
				this.calendarDays.forEach(d => d.isSelected = false);

				// 选中新的一天
				day.isSelected = true;
				this.selectedCalendarDate = day.fullDate; // 使用日期对象中的完整日期
				this.selectedDate = day.fullDate; // 同步到搜索栏

				// 获取该日期所有的课程
				const lessons = this.currentMonthLessons.filter(lesson => lesson.specificDate === day.fullDate);
				if (lessons.length > 0) {
					this.selectedLessonDetails = lessons;
				} else {
					this.selectedLessonDetails = null;
				}
			},
			generateCalendarDays() {
				this.calendarDays = [];
				const firstDayOfMonth = new Date(this.currentYear, this.currentMonth - 1, 1);
				// 调整起始日为周一 (0表示周日，1表示周一，...，6表示周六)
				let startDay = firstDayOfMonth.getDay();
				if (startDay === 0) startDay = 7; // 如果是周日，则设为7，以便周一为1
				startDay = startDay - 1; // 调整为0-indexed，其中周一为0

				const daysInMonth = new Date(this.currentYear, this.currentMonth, 0).getDate();
				const daysInPrevMonth = new Date(this.currentYear, this.currentMonth - 1, 0).getDate();

				// 添加上个月的日期 (灰色显示)
				for (let i = startDay - 1; i >= 0; i--) {
					this.calendarDays.push({
						day: daysInPrevMonth - i,
						isCurrentMonth: false,
						hasLesson: false,
						isSelected: false,
						fullDate: null
					});
				}

				// 添加当前月份的日期
				for (let i = 1; i <= daysInMonth; i++) {
					const dateString = `${this.currentYear}-${this.currentMonth < 10 ? '0' + this.currentMonth : this.currentMonth}-${i < 10 ? '0' + i : i}`;
					const hasLesson = this.currentMonthLessons.some(lesson => lesson.date === dateString);
					const isSelected = this.selectedCalendarDate === dateString;
					this.calendarDays.push({
						day: i,
						isCurrentMonth: true,
						hasLesson: hasLesson,
						isSelected: isSelected,
						fullDate: dateString
					});
				}

				// 添加下个月的日期 (灰色显示)，以填满网格 (6行 x 7天，最多42天)
				const remainingCells = 42 - this.calendarDays.length;
				for (let i = 1; i <= remainingCells; i++) {
					this.calendarDays.push({
						day: i,
						isCurrentMonth: false,
						hasLesson: false,
						isSelected: false,
						fullDate: null
					});
				}
			},
			goToPreviousMonth() {
				this.showDetailedSearch = false;
				if (this.currentMonth === 1) {
					this.currentMonth = 12;
					this.currentYear--;
				} else {
					this.currentMonth--;
				}
				this.selectedCalendarDate = null;
				this.selectedLessonDetails = null;
				this.calendarDays.forEach(d => d.isSelected = false);
				this.fetchLessonsForMonth(this.currentYear, this.currentMonth);
			},
			goToNextMonth() {
				this.showDetailedSearch = false;
				if (this.currentMonth === 12) {
					this.currentMonth = 1;
					this.currentYear++;
				} else {
					this.currentMonth++;
				}
				this.selectedCalendarDate = null;
				this.selectedLessonDetails = null;
				this.calendarDays.forEach(d => d.isSelected = false);
				this.fetchLessonsForMonth(this.currentYear, this.currentMonth);
			},
			// 日历点击日期
			onCalendarDayClick(day) {
				if (!day.isCurrentMonth) return;
				this.selectedDate = day.fullDate; // 同步到搜索栏
				this.selectCalendarDate(day); // 选中并查课表
			}
		}
	}
</script>

<style>
	.container {
		box-sizing: border-box;
		padding-bottom: 100rpx;
		background-color: #f5f5f5;
		font-family: Arial, sans-serif;
	}

	/* Header */
	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px 15px;
		background-color: #fff;
		border-bottom: 1px solid #eee;
	}

	.time {
		font-size: 15px;
		font-weight: bold;
	}

	.placeholder{
		height:29.2px ;
		width: 160px;
	}
	.status-icons {
		display: flex;
		gap: 5px;
		font-size: 14px;
	}

	/* User Info Section */
	.user-info-section {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #2C57F6;
		padding: 20px 15px;
		color: #fff;
		border-radius: 0 0 15px 15px;
		margin-bottom: 10px;
	}

	.dropdowns {
		display: flex;
		flex-direction: column;
		gap: 10px;
	}

	.dropdown-item {
		display: flex;
		align-items: center;
		background-color: #fff;
		border-radius: 5px;
		padding: 5px 20px;
		font-size: 14px;
		color: #333;
		min-width: 120px;
		justify-content: space-between;
	}

	.dropdown-item .arrow {
		margin-left: 5px;
		font-size: 10px;
	}

	.lesson-count {
		font-size: 12px;
		opacity: 0.8;
		margin-top: 5px;
		font-size: 15px;
	}

	.avatar {
		width: 80px;
		height: 80px;
		border-radius: 50%;
		border: 2px solid #fff;
		margin-right: 50px;
		
	}

	/* Calendar Section */
	.calendar-section {
		background-color: #fff;
		margin: 8px 12px;
		border-radius: 12px;
		padding: 16px;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
	}

	.calendar-nav {
		display: none; /* Hide the old calendar-nav */
	}

	.calendar-search-row {
		display: flex;
		justify-content: center;
		margin-bottom: 15px;
		padding: 4px;
	}

	.calendar-month-nav-row {
		display: flex;
		color: #4296E5;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10px;
		font-size: 15px;
	}

	.search-box {
		display: flex;
		color: #4296E5;
		font-size: 17px;
		font-weight: 700;
		align-items: center;
		background-color: #fff;
		border-radius: 20px;
		padding: 5px 10px;
	}

	.search-icon {
		margin-right: 5px;
	}

	.search-text {
		margin-right: 5px;
	}

	.month {
		font-weight: bold;
		color: #333;
		font-size: 16px;
	}

	.calendar-grid {
		display: flex;
		flex-direction: column;
	}

	.weekday-header,
	.days-row {
		display: flex;
		justify-content: space-around;
		margin-bottom: 8px;
	}

	.weekday-header text,
	.day {
		width: 28px;
		height: 28px;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 15px;
		color: #333;
	}

	.weekday-header text {
		color: #999;
	}

	.day.gray {
		color: #ccc;
	}

	.day.selected {
		background-color: #3b7bff;
		color: #fff;
		border-radius: 50%;
	}

	/* Course Info Section */
	.course-info-section {
		background-color: #fff;
		margin: 0 8px 8px 8px;
		border-radius: 10px;
		padding: 15px;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
	}

	.time-display {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
		font-size: 14px;
		color: #3b7bff;
	}

	.time-icon {
		margin-right: 5px;
	}

	.course-name,
	.class-name {
		font-size: 15px;
		margin-left: 30px;
		color: #333;
		margin-bottom: 5px;
	}

	.lesson-item {
		padding: 10px 0;
	}

	.divider {
		height: 1px;
		background-color: #eee;
		margin: 10px 0;
	}

	/* Bottom Navigation Bar */
	.bottom-nav-bar {
		display: flex;
		justify-content: space-around;
		align-items: center;
		background-color: #fff;
		padding: 10px 0;
		border-top: 1px solid #eee;
		position: fixed;
		bottom: 0;
		width: 100%;
	}

	.nav-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		font-size: 12px;
		color: #666;
	}

	.nav-item .icon {
		font-size: 22px;
		margin-bottom: 3px;
	}

	.ai-button {
		background-color: #3b7bff;
		width: 50px;
		height: 50px;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #fff;
		font-weight: bold;
		font-size: 18px;
		margin-top: -20px; /* Adjust to lift the button */
		box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
	}

	.ai-button .icon-ai {
		font-size: 24px;
	}

	.detailed-search-form {
		display: flex;
		flex-direction: column;
		background-color: #fff;
		border-radius: 10px;
		padding: 15px;
		width: 90%;
		margin: 0 auto;
	}

	.search-header {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 15px;
		font-size: 17px;
		font-weight: 700;
		color: #4296E5;
	}

	.date-input-row {
		display: flex;
		align-items: center;
		border: 1px solid #eee;
		border-radius: 5px;
		padding: 8px 10px;
		color: #666;
		/* margin-bottom: 15px; */
	}

	.date-label {
		color: #666;
		margin-right: 10px;
		font-size: 14px;
	}

	.date-input {
		flex: 1;
		border: none;
		outline: none;
		font-size: 14px;
		color: #333;
	}

	.buttons-row {
		display: flex;
		justify-content: space-around;
		gap: 15px;
	}

	.reset-button,
	.query-button {
		flex: 1;
		padding: 5px 0;
		border-radius: 20px;
		font-size: 14px;
		font-weight: bold;
		border: none;
		outline: none;
		cursor: pointer;
	}

	.reset-button {
		background-color: #fff;
		color: #666;
		border: 1px solid #ddd;
	}

	.query-button {
		background-color: #4296E5;
		color: #fff;
	}

	.course-info-scroll {
		margin: 0 8px 8px 8px;
		padding-bottom: 60px;
	}
</style>
